/**
 * fshows.com
 * Copyright (C) 2013-2019 All Rights Reserved.
 */
package com.fshows.leshuapay.sdk.util;

import com.alibaba.fastjson.JSONObject;
import com.fshows.leshuapay.sdk.exception.LeshuaException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author wujn
 * @version FsHttpUtil.java, v 0.1 2019-05-15 16:07 wujn
 */
@Slf4j
public class FsHttpUtil {
    public static final String ACCEPT_TYPE_XML = "application/xml";
    public static final int DEFAULT_SO_TIMEOUT = 10000;
    public static final int DEFAULT_CONN_TIMEOUT = 6000;
    public static final int DEFAULT_CONN_REQ_TIMEOUT = 5000;
    private static final String DEFAULT_CHARSET = StringPool.UTF_8;
    private static final String METHOD_POST = "POST";
    private static final String METHOD_GET = "GET";
    /**
     * 10S超时
     */
    private static final int DEFAULT_READ_TIMEOUT = 10 * 1000;
    private static final int DEFAULT_CONNECTION_TIMEOUT = 3 * 1000;
    private static final String DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded;charset=utf-8";
    private static final String JSON_CONTENT_TYPE = "application/json;charset=utf-8";
    private static HostnameVerifier verifier = null;
    private static SSLSocketFactory socketFactory = null;

    static {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()},
                    new SecureRandom());
            ctx.getClientSessionContext().setSessionTimeout(15);
            ctx.getClientSessionContext().setSessionCacheSize(1000);
            socketFactory = ctx.getSocketFactory();
        } catch (Exception ignored) {
        }
        verifier = (hostname, session) -> true;
    }

    /**
     * Trust every server - dont check for any certificate
     */
    public static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
        }};

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * @param url
     * @param params
     * @param charset
     * @param contentType
     * @param connectTimeout
     * @param readTimeout
     * @param headers
     * @return
     * @throws IOException
     */
    public static String post(String url, Map<String, String> params, String charset, String contentType,
                              int connectTimeout, int readTimeout, Map<String, String> headers) throws IOException {
        if (StringUtils.isBlank(url)) {
            throw new IllegalArgumentException("url is empty");
        }
        if (StringUtils.isBlank(charset)) {
            charset = DEFAULT_CHARSET;
        }
        if (StringUtils.isBlank(contentType)) {
            contentType = DEFAULT_CONTENT_TYPE;
        }
        if (connectTimeout <= 0) {
            connectTimeout = DEFAULT_CONNECTION_TIMEOUT;
        }
        if (readTimeout <= 0) {
            readTimeout = DEFAULT_READ_TIMEOUT;
        }
        HttpURLConnection conn = null;
        OutputStream out = null;
        String rsp = null;
        String query = buildQuery(params, charset);
        byte[] content = {};
        if (StringUtils.isNotBlank(query)) {
            content = query.getBytes(charset);
        }
        try {
            conn = getConnection(new URL(url), METHOD_POST, contentType, headers);
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } finally {
            if (out != null) {
                out.close();
            }
            if (conn != null) {
                conn.disconnect();

            }
        }
        return rsp;
    }

    /**
     * @param url
     * @param data
     * @param charset
     * @param contentType
     * @param connectTimeout 毫秒
     * @param readTimeout    毫秒
     * @param headers
     * @return
     * @throws IOException
     */
    public static String postString(String url, String data, String charset, String contentType,
                                    int connectTimeout, int readTimeout, Map<String, String> headers) throws IOException {
        if (StringUtils.isBlank(url)) {
            throw new IllegalArgumentException("url is empty");
        }
        if (StringUtils.isBlank(charset)) {
            charset = DEFAULT_CHARSET;
        }
        if (StringUtils.isBlank(contentType)) {
            contentType = JSON_CONTENT_TYPE;
        }
        if (connectTimeout <= 0) {
            connectTimeout = DEFAULT_CONNECTION_TIMEOUT;
        }
        if (readTimeout <= 0) {
            readTimeout = DEFAULT_READ_TIMEOUT;
        }
        HttpURLConnection conn = null;
        OutputStream out = null;
        String rsp = null;
        byte[] content = {};
        if (StringUtils.isNotBlank(data)) {
            content = data.getBytes(charset);
        }
        try {
            conn = getConnection(new URL(url), METHOD_POST, contentType, headers);
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } finally {
            if (out != null) {
                out.close();
            }
            if (conn != null) {
                conn.disconnect();

            }
        }
        return rsp;
    }

    public static String uploadFile(String url, byte[] file, String charset, String contentType,
                                    int connectTimeout, int readTimeout, Map<String, String> headers) throws IOException {
        if (StringUtils.isBlank(url)) {
            throw new IllegalArgumentException("url is empty");
        }
        if (StringUtils.isBlank(contentType)) {
            contentType = JSON_CONTENT_TYPE;
        }
        if (connectTimeout <= 0) {
            connectTimeout = DEFAULT_CONNECTION_TIMEOUT;
        }
        if (readTimeout <= 0) {
            readTimeout = DEFAULT_READ_TIMEOUT;
        }
        HttpURLConnection conn = null;
        OutputStream out = null;
        String rsp = null;
        try {
            conn = getConnection(new URL(url), METHOD_POST, contentType, headers);
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
            out = conn.getOutputStream();
            out.write(file);
            rsp = getResponseAsString(conn);
        } finally {
            if (out != null) {
                out.close();
            }
            if (conn != null) {
                conn.disconnect();

            }
        }
        return rsp;
    }

    /**
     * @param url
     * @param params
     * @param charset
     * @param connectTimeout 毫秒
     * @param readTimeout    毫秒
     * @param contentType
     * @param headers
     * @return
     * @throws IOException
     */
    public static String get(String url, Map<String, String> params, String contentType,
                             String charset, int connectTimeout, int readTimeout, Map<String, String> headers) throws IOException {
        if (StringUtils.isBlank(url)) {
            throw new IllegalArgumentException("url is empty");
        }
        if (StringUtils.isBlank(charset)) {
            charset = DEFAULT_CHARSET;
        }
        if (StringUtils.isBlank(contentType)) {
            contentType = DEFAULT_CONTENT_TYPE;
        }
        if (connectTimeout <= 0) {
            connectTimeout = DEFAULT_CONNECTION_TIMEOUT;
        }
        if (readTimeout <= 0) {
            readTimeout = DEFAULT_READ_TIMEOUT;
        }
        HttpURLConnection conn = null;
        String rsp = null;
        try {
            String query = buildQuery(params, charset);
            conn = getConnection(buildGetUrl(url, query), METHOD_GET, contentType, headers);
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
            rsp = getResponseAsString(conn);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rsp;
    }

    public static String get(String url) throws IOException {
        return get(url, DEFAULT_READ_TIMEOUT);
    }

    public static String get(String url, int timeout) throws IOException {
        return get(url, null, DEFAULT_CHARSET, DEFAULT_CONTENT_TYPE, DEFAULT_CONNECTION_TIMEOUT, timeout, null);
    }

    public static String post(String url, Map<String, String> param) throws IOException {
        return post(url, param, DEFAULT_READ_TIMEOUT);
    }

    public static String post(String url, Map<String, String> param, int timeout) throws IOException {
        return post(url, param, DEFAULT_CHARSET, DEFAULT_CONTENT_TYPE, DEFAULT_CONNECTION_TIMEOUT, timeout, null);
    }

    private static URL buildGetUrl(String strUrl, String query) throws IOException {
        URL url = new URL(strUrl);
        if (StringUtils.isEmpty(query)) {
            return url;
        }

        if (StringUtils.isEmpty(url.getQuery())) {
            if (strUrl.endsWith("?")) {
                strUrl = strUrl + query;
            } else {
                strUrl = strUrl + "?" + query;
            }
        } else {
            if (strUrl.endsWith("&")) {
                strUrl = strUrl + query;
            } else {
                strUrl = strUrl + "&" + query;
            }
        }

        return new URL(strUrl);
    }

    private static String getResponseCharset(String ctype) {
        String charset = DEFAULT_CHARSET;
        if (!StringUtils.isEmpty(ctype)) {
            String[] params = ctype.split(";");
            for (String param : params) {
                param = param.trim();
                if (param.startsWith("charset")) {
                    String[] pair = param.split("=", 2);
                    if (pair.length == 2) {
                        if (!StringUtils.isEmpty(pair[1])) {
                            charset = pair[1].trim();
                        }
                    }
                    break;
                }
            }
        }
        return charset;
    }

    private static String getStreamAsString(InputStream stream, String charset) throws IOException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
            StringWriter writer = new StringWriter();
            char[] chars = new char[256];
            int count = 0;
            while ((count = reader.read(chars)) > 0) {
                writer.write(chars, 0, count);
            }
            return writer.toString();
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }

    private static String getResponseAsString(HttpURLConnection conn) throws IOException {
        String charset = getResponseCharset(conn.getContentType());
        InputStream es = conn.getErrorStream();
        if (es == null) {
            return getStreamAsString(conn.getInputStream(), charset);
        } else {
            String msg = getStreamAsString(es, charset);
            if (StringUtils.isEmpty(msg)) {
                throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
            } else {
                throw new IOException(msg);
            }
        }
    }

    private static String buildQuery(Map<String, String> params, String charset) throws IOException {
        if (params == null || params.isEmpty()) {
            return null;
        }
        StringBuilder query = new StringBuilder();
        Set<Map.Entry<String, String>> entries = params.entrySet();
        boolean hasParam = false;
        for (Map.Entry<String, String> entry : entries) {
            String name = entry.getKey();
            String value = entry.getValue();
            // 忽略参数名或参数值为空的参数
            if (StringUtils.isNotBlank(name)) {
                if (hasParam) {
                    query.append("&");
                } else {
                    hasParam = true;
                }
                query.append(name).append("=").append(URLEncoder.encode(value, charset));
            }
        }
        return query.toString();
    }

    private static HttpURLConnection getConnection(URL url, String method, String contentType, Map<String, String> headers) throws IOException {
        HttpURLConnection conn = null;
        if ("https".equals(url.getProtocol())) {
            HttpsURLConnection connHttps = null;
            connHttps = (HttpsURLConnection) url.openConnection();
            connHttps.setSSLSocketFactory(socketFactory);
            connHttps.setHostnameVerifier(verifier);
            conn = connHttps;
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml,application/json;q=0.9,*/*;q=0.8");
        conn.setRequestProperty("Accept-Encoding", "gzip");
        conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36 FsHttpUtil");
        if (headers != null && headers.size() > 0) {
            headers.forEach(conn::setRequestProperty);
        }
        return conn;
    }

    /**
     * 文件上传
     *
     * @param url
     * @param map
     * @param file
     * @param timeOut
     * @return
     * @throws Exception
     */
    public static String postMedia(String url, Map<String, String> map, File file, int timeOut) {
        HttpPost httppost = new HttpPost(url);
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setCharset(StandardCharsets.UTF_8);
        multipartEntityBuilder.setContentType(ContentType.MULTIPART_FORM_DATA);
        multipartEntityBuilder.addPart("agentId", new StringBody(map.get("agentId"), ContentType.APPLICATION_JSON));
        multipartEntityBuilder.addPart("version", new StringBody(map.get("version"), ContentType.APPLICATION_JSON));
        multipartEntityBuilder.addPart("reqSerialNo", new StringBody(map.get("reqSerialNo"), ContentType.APPLICATION_JSON));
        multipartEntityBuilder.addPart("data", new StringBody(map.get("data"), ContentType.APPLICATION_JSON));
        multipartEntityBuilder.addPart("sign", new StringBody(map.get("sign"), ContentType.APPLICATION_JSON));

        //图片文件
        multipartEntityBuilder.addPart("media", new FileBody(file));
        HttpEntity reqEntity = multipartEntityBuilder.build();
        httppost.setEntity(reqEntity);
        //设置超时时间
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(15 * 1000)
                .setConnectionRequestTimeout(timeOut == 0 ? 5 * 1000 : timeOut)
                .setSocketTimeout(timeOut == 0 ? 30 * 1000 : timeOut).build();
        log.info("RequestConfig，config={}", JSONObject.toJSONString(config));
        httppost.setConfig(config);
        String result = "";
        HttpEntity resEntity = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                }
            } else {
                throw new LeshuaException("文件上传失败");
            }
        } catch (LeshuaException e) {
            log.error("postMedia >> 文件上传失败,response={}, e={}", response, e);
        } catch (Exception e) {
            log.error("图片上传失败,ex={}", e);
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(resEntity);
            } catch (IOException e) {
                log.error("释放HttpEntity错误，错误信息：" + e.getMessage(), e);
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("关闭HttpResponse出错，错误信息：" + e.getMessage(), e);
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.error("关闭HttpClient出错，错误信息：" + e.getMessage(), e);
                }
            }
        }
        return result;
    }

    public static String postFileMedia(String url, Map<String, String> map, File file, int timeOut) {
        HttpPost httppost = new HttpPost(url);
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
        multipartEntityBuilder.setContentType(ContentType.MULTIPART_FORM_DATA);
        multipartEntityBuilder.addPart("agentId", new StringBody(map.get("agentId"), ContentType.APPLICATION_JSON));
        multipartEntityBuilder.addPart("version", new StringBody(map.get("version"), ContentType.APPLICATION_JSON));
        multipartEntityBuilder.addPart("reqSerialNo", new StringBody(map.get("reqSerialNo"), ContentType.APPLICATION_JSON));
        multipartEntityBuilder.addPart("data", new StringBody(map.get("data"), ContentType.APPLICATION_JSON));
        multipartEntityBuilder.addPart("sign", new StringBody(map.get("sign"), ContentType.APPLICATION_JSON));

        //图片文件
        multipartEntityBuilder.addPart("media", new FileBody(file));
        HttpEntity reqEntity = multipartEntityBuilder.build();
        httppost.setEntity(reqEntity);
        //设置超时时间
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(90 * 1000)
                .setConnectionRequestTimeout(timeOut == 0 ? 90 * 1000 : timeOut)
                .setSocketTimeout(timeOut == 0 ? 90 * 1000 : timeOut).build();
        log.info("RequestConfig，config={}", JSONObject.toJSONString(config));
        httppost.setConfig(config);
        httppost.setProtocolVersion(HttpVersion.HTTP_1_0);
        String result = "";
        HttpEntity resEntity = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httppost);
            log.info("postFileMedia，response={}", JSONObject.toJSONString(response));
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resEntity = response.getEntity();
                log.info("postFileMedia，resEntity={}", JSONObject.toJSONString(resEntity));
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                }
            } else {
                throw new LeshuaException("文件上传失败");
            }
        } catch (LeshuaException e) {
            log.error("postFileMedia >> 文件上传失败,response={}, e={}", response, e);
        } catch (Exception e) {
            log.error("postFileMedia >> 图片上传失败,ex={}", e);
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(resEntity);
            } catch (IOException e) {
                log.error("释放HttpEntity错误，错误信息：" + e.getMessage(), e);
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("关闭HttpResponse出错，错误信息：" + e.getMessage(), e);
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.error("关闭HttpClient出错，错误信息：" + e.getMessage(), e);
                }
            }
        }
        return result;
    }

    /**
     * post请求，默认utf-8编码，指定格式
     *
     * @param url
     * @param formParams
     * @param acceptType
     * @return
     */
    public String postForm(String url, Map<String, String> formParams, String acceptType, Integer timeout) {
        return this.postForm(url, formParams, acceptType, null, SignUtil.DEFAULT_CHARSET, timeout);
    }

    /**
     * post请求，指定编码，指定格式，需要授权
     *
     * @param url
     * @param formParams
     * @param acceptType
     * @param auth
     * @param charset
     * @param timeout
     * @return
     */
    public String postForm(String url, Map<String, String> formParams, String acceptType, String auth, String charset, Integer timeout) {
        List<NameValuePair> urlParameters = new ArrayList<>();
        if (formParams != null) {
            for (Map.Entry<String, String> entry : formParams.entrySet()) {
                urlParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        HttpEntity requestEntity = null;
        try {
            requestEntity = new UrlEncodedFormEntity(urlParameters, charset);
            return this.postForm(url, requestEntity, acceptType, auth, charset, timeout);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        } catch (Throwable e) {
            log.error("请求失败！formParams={},url={},errorMsg={}", formParams, url, e.getMessage());
            throw e;
        }
        return null;
    }

    /**
     * post请求，指定编码，指定格式，需要授权
     *
     * @param url
     * @param requestEntity
     * @param acceptType
     * @param auth
     * @param charset
     * @param timeout
     * @return
     */
    private String postForm(String url, HttpEntity requestEntity, String acceptType, String auth, String charset, Integer timeout) {
        String result = null;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        RequestConfig requestConfig = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            if (timeout == null) {
                // 设置默认http状态参数
                requestConfig = RequestConfig.custom().setSocketTimeout(DEFAULT_SO_TIMEOUT).setConnectTimeout(DEFAULT_CONN_TIMEOUT)
                        .setConnectionRequestTimeout(DEFAULT_CONN_REQ_TIMEOUT).build();
                httpPost.setConfig(requestConfig);
            } else {
                requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
                        .setConnectionRequestTimeout(timeout).build();
                httpPost.setConfig(requestConfig);
            }
            httpPost.setHeader("Accept", acceptType);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
            if (auth != null) {
                httpPost.setHeader("Authorization", auth);
            }
            httpPost.setEntity(requestEntity);
            if (StringUtils.startsWithIgnoreCase(url, "https")) {
                trustAllHosts();
            }
            // 执行客户端请求
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, charset);
            }
        } catch (Exception e) {
            log.error("请求失败,e={}", ExceptionUtils.getStackTrace(e));
        } finally {
            // 关闭连接
            if (entity != null) {
                EntityUtils.consumeQuietly(entity);
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("关闭HttpResponse出错，错误信息：" + e.getMessage(), e);
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.error("关闭HttpClient出错，错误信息：" + e.getMessage(), e);
                }
            }
        }
        return result;
    }

    private static class DefaultTrustManager implements X509TrustManager {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain,
                                       String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain,
                                       String authType) throws CertificateException {
        }
    }
}
